import 'dart:convert';

import 'package:example_example/services/ScreenAdapter.dart';
import 'package:example_example/services/TLSizeFit.dart';

import '../../pages/view/LoadingView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../bean/BaseBean.dart';
import '../../global/Global.dart';
import '../../global/GlobalUrl.dart';
import '../../util/HttpUtil.dart';
import '../../util/LogUtil.dart';
import '../../util/ToastUtils.dart';
import '../../util/Storage.dart';
import '../view/ItemToDoTaskView.dart';
import '../../bean/order/AutogeneratedBean.dart';
import '../../pages/person/Login.dart';
import '../view/ItemhistoryTaskView.dart';
import '../view/HeaderView.dart';
import '../view/NoDataView.dart';

/**刷新来自官网的demo
 * flutter_easyrefresh   刷新的第三方组件
 * https://pub.dev/packages/flutter_easyrefresh/example
 *
 * 历史任务
 *
 */

class HistoryTaskPage extends StatefulWidget {
  HistoryTaskPage({Key key}) : super(key: key);

  _HistoryTaskPageState createState() => _HistoryTaskPageState();
}

class _HistoryTaskPageState extends State<HistoryTaskPage> {
  EasyRefreshController _controller;

  // 条目总数
//  int _count = 6; //20

  List dataList = [];
  int pageIndex = 1;
  bool noDataflag = false;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();

    initHttpData();
  }

  @override
  Widget build(BuildContext context) {
    TLSizeFit.initialize();
    ScreenAdapter.init(context);

    return Scaffold(
//        appBar: AppBar(
//          title: Text("EasyRefresh"),
//        ),
      appBar: HeaderView(
        title: "历史任务",
        isShowReturnArrow: true,
      ),
      body: Stack(children: <Widget>[
        EasyRefresh.custom(
          enableControlFinishRefresh: false,
          // 是否开启控制结束刷新
          enableControlFinishLoad: true,
          // 是否开启控制结束加载
          controller: _controller,
          // EasyRefresh控制器
//          header: ClassicalHeader(),
          header: ClassicalHeader(
            enableInfiniteRefresh: false,
            refreshText: "拉动刷新",
            refreshReadyText: "释放刷新",
            refreshingText: "正在刷新...",
            refreshedText: "刷新完成",
            refreshFailedText: "刷新失败",
            noMoreText: "没有更多数据",
            showInfo: false, // 是否显示时间
//            infoText: "更新于 %T",
          ),
//          footer: ClassicalFooter(),
          footer: ClassicalFooter(
            loadText: "拉动加载",
            loadReadyText: "释放加载",
            loadingText: "正在加载...",
            loadedText: "加载完成",
            loadFailedText: "加载失败",
            noMoreText: "没有更多数据",
            infoText: "更新于 %T",
          ),
          onRefresh: () async {
            print('onRefresh');
            pageIndex = 1;
            initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
//          });
          },
          onLoad: () async {
            print('onLoad');
            pageIndex++;
            initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
////            _controller.finishLoad(noMore: _count >= 40);
//          });
          },
          slivers: <Widget>[
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  if (dataList != null && dataList.length > 0) {
                    return InkWell(
                      child: ItemHistoryTaskView(context, dataList[index], "2"),
//                    child: ItemToDoTaskView(context,dataList[index]),
                      onTap: () {
//                      Navigator.pushNamed(context, '/webViewUtilPage',
//                          arguments: {Global.WEBVIEW_TAG: Global.HELP}).then((value) {
//                        print('webview:$value');
//                      });
//                      Navigator.pushNamed(context, '/webViewUtilPage',
//                          arguments: {
//                            Global.WEBVIEW_TAG: Global.HIISTORYTASK,
//                            "id":dataList[index]["id"],
//                          }).then((value) {
//                        print('webview:$value');
//                      });

                        String processDefinitionKey =
                            dataList[index]["processDefinitionKey"];
                        String processInstanceId = dataList[index]["processInstanceId"];
                        print(
                            "列表数据 processDefinitionKey:$processDefinitionKey"); //taskDefinitionKey
                        print("列表数据 processInstanceId:$processInstanceId");
                        if (processDefinitionKey == null) {
                          processDefinitionKey = "";
                        }
                        if (processInstanceId == null) {
                          processInstanceId = "";
                        }

                        String url = GlobalUrl.WEB_HISTORY_URL +
                            "?processInstanceId=" +
                            processInstanceId +
                            "&processDefinitionKey=" +
                            processDefinitionKey +
                            "&platform=app";
                        Navigator.pushNamed(
                            context, '/webViewUtilPage', //WebViewExample
                            arguments: {
                              Global.WEBVIEW_TAG: Global.HIISTORYTASK,
                              Global.WEBVIEW_URL: url,
                              "id": dataList[index]["id"],
                              'dataStr': dataList[index],
                            }).then((value) {
                          print('webview:$value');
                        });
                      },
                    );
//                  return ItemHistoryTaskView(dataList[index]);
                  } else {
                    return Container(
                      width: 60.0,
                      height: 60.0,
                      child: Center(
                        child: Text('$index'),
                      ),
                      color: index % 2 == 0
                          ? Colors.grey[300]
                          : Colors.transparent,
                    );
                  }

//                return Container(
//                  width: 60.0,
//                  height: 60.0,
//                  child: Center(
//                    child: Text('$index'),
//                  ),
//                  color: index % 2 == 0 ? Colors.grey[300] : Colors.transparent,
//                );

//
                },
                childCount: dataList.length,
              ),
            ),
          ],
        ),
        (this.dataList.length <= 0 && !noDataflag) ? LoadingView() : Container(),
        noDataflag ? NoDataView(): Container(),

      ]),
    );
  }

  initHttpData() async {
//    http://10.66.1.100:8181/api/us-process/process/pageFinished?current=1&size=10

    String apiUrlhttp = GlobalUrl.PROCESSHISTORY;
    var map = {
      "current": pageIndex,
      "size": "10",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp,context:this.context, data: map, headers: mapHeaders, success: (data) {
      // 下拉刷新停止
      _controller.resetLoadState();
      //  上拉加载停止
      _controller.finishLoadCallBack();
//    _controller.finishLoad(noMore: false);
      _controller.finishLoad();

      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了");
        List getList = body["records"];
//        LogUtil.v("getList:$getList");
        LogUtil.v(getList.length);

        if (pageIndex == 1) {
          dataList.clear();
          dataList.addAll(getList);
        } else {
          dataList.addAll(getList);
        }
        print(dataList.length);

        if (dataList.length == 0) {
          setState(() {
            noDataflag = true;
          });
        } else {
          setState(() {
            dataList = dataList;
            noDataflag = false;
          });
        }

//        for (var i = 0; i < getList.length; i++) {
//          var ppProjectName = getList[i]["ppProjectName"];
//          LogUtil.v("ppProjectName:$ppProjectName");
//          var variableJson = getList[i]['variableJson'];
////          LogUtil.v("variableJson:$variableJson");
//          variableJson = json.decode(variableJson);
//          var biProjectName = variableJson["biProjectName"];
//          LogUtil.v("biProjectName:$biProjectName");
//        }
      } else {
        if (message != null) {
          ToastUtils.toast(message);
        }
        if (code == "401") {
          //用户登录超时
          print("超时了啊");
          Storage.clear(); // 清除数据
          //跳转并关闭当前页面
          Navigator.pushAndRemoveUntil(
            context,
            new MaterialPageRoute(builder: (context) => new LoginPage()),
            (route) => route == null,
          );
        }
      }
    }, error: (errorMsg) {
      print("待办任务..历史任务..errorMsg: $errorMsg");
      // 下拉刷新停止
      _controller.resetLoadState();

      //  上拉加载停止
      _controller.finishLoadCallBack();
//            _controller.finishLoad(noMore: false);
      _controller.finishLoad();
    });
  }
}
